package MicronautTest;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.annotation.Filter;
import io.micronaut.http.filter.HttpServerFilter;
import io.micronaut.http.filter.ServerFilterChain;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;
import org.reactivestreams.Publisher;

import java.io.File;
import java.util.logging.Logger;

@Filter("/helloaa/**")
public class PartialContentFilter implements HttpServerFilter {
    Logger log = Logger.getLogger("PartialContentFilter");

    @Override
    public Publisher<MutableHttpResponse<?>> doFilter(HttpRequest<?> request, ServerFilterChain chain) {
        log.info("uri:" + request.getUri());
        log.info("path:" + request.getPath());
        log.info("params:" + request.getParameters().get("p"));

        return Flowable.fromCallable(()->{
            log.info("fromCallable");
            return new File("ha"); // true to intercept and false to pass
        })
        .subscribeOn(Schedulers.io())
        .switchMap(aBoolean -> {
            log.info("switchMap:" + aBoolean.getName());

//            if (aBoolean) {
//                MutableHttpResponse<String> response = HttpResponse.status(HttpStatus.FORBIDDEN).body("forbidden haha");
//                return Publishers.just(response);
//            } else {
//                return chain.proceed(request);
//            }
            return chain.proceed(request);
        })
        .doOnNext(res->{
            // called after Publishers.just(response) or chain.proceed(request)
            log.info("doOnNext, httpResponse:" + res + "/" + res.getBody());
        });

//        return chain.proceed(request);
    }

}
